package server;

import java.util.Collection;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public final class Mapper {

    MappedHost[] mappedHosts;


    protected abstract static class MapElement<T> {

        public final String name;
        public final T object;

        public MapElement(String name, T object) {
            this.name = name;
            this.object = object;
        }
    }

    protected static final class MappedHost extends MapElement<Host> {

        MappedContext[] mappedContexts;

        public MappedHost(String name, Host object) {
            super(name, object);
        }
    }

    protected static final class MappedContext extends MapElement<Context> {
        MappedWrapper[] mappedWrappers;

        public MappedContext(String name, Context object) {
            super(name, object);
        }
    }

    protected static final class MappedWrapper extends MapElement<Wrapper> {


        public MappedWrapper(String name, Wrapper object) {
            super(name, object);
        }
    }


    public MappingData map(Request request) {
        String url = request.getUrl().substring(1);
        String context = url.split("/")[0];
        String servlet = url.split("/")[1];

        String host = request.getHost();
        MappingData mappingData = new MappingData();

        MappedHost mHost = null;
        MappedContext mContext = null;
        MappedWrapper mWrapper = null;

        for (MappedHost mappedHost : mappedHosts) {
            if (mappedHost.name.equals(host)) {

                mHost = mappedHost;
                break;
            }
        }

        if (mHost != null) {

            mappingData.setHost(mHost.object);
            for (MappedContext mappedContext : mHost.mappedContexts) {
                if (mappedContext.name.equals(context)) {
                    mContext = mappedContext;
                    break;
                }
            }
        }

        if (mContext != null) {
            mappingData.setContext(mContext.object);

            for (MappedWrapper mappedWrapper : mContext.mappedWrappers) {
                if (mappedWrapper.name.toLowerCase().contains(servlet.toLowerCase())) {
                    mWrapper = mappedWrapper;
                }
            }
        }

        if (mWrapper != null) {

            mappingData.setWrapper(mWrapper.object);
        }
        return mappingData;
    }


}








